import { defineStore } from "pinia";
import { ref, computed } from "vue";

// 初始状态
function initState() {
    return {
        // 银行卡列表
        bankCards: [],
        // 加载状态
        loading: false,
        // 是否已加载数据
        isLoaded: false
    };
}

export const useBankCardStore = defineStore("bankCardStore", () => {
    // 状态
    const state = ref(initState());

    // 计算属性
    const bankCards = computed(() => state.value.bankCards);
    const loading = computed(() => state.value.loading);
    const isLoaded = computed(() => state.value.isLoaded);
    const defaultCard = computed(() => state.value.bankCards.find(card => card.isDefault === 1) || null);
    const bankCardCount = computed(() => state.value.bankCards.length);

    // 银行卡列表缓存
    function setBankCards(bankCards) {
        state.value.bankCards = bankCards || [];
        state.value.isLoaded = false;
    }

    // 重置状态
    function resetState() {
        Object.assign(state.value, initState());
    }

    return {
        state,
        bankCards,
        loading,
        isLoaded,
        defaultCard,
        bankCardCount,
        setBankCards,
        resetState
    };
}, {
    persist: {
        key: 'bank-card-store',
        storage: localStorage,
        paths: ['state.bankCards', 'state.isLoaded']
    }
});